<?php

namespace App\Models;

use Carbon\Carbon;

class Sharp extends BaseModel
{
    protected $fillable = [
    	'store_id',
    	'active_name',
    	'active_start',
    	'active_end'
    ];

    public function sharpGoods()
    {
    	return $this->hasMany(SharpToGoods::class, 'sharp_id', 'id');
    }
    
    public function sharptogoods()
    {
    	return $this->hasMany(SharpToGoods::class);
    }

    /**
    * 检查活动时间不交叉，以免商品出现在两个不同活动中
    * @param   $active_start [<活动开始时间>]
    * @return  bool [<通过则为true>]
    */
    public function checkActiveTime($active_start, $store_id)
    {
    	if (empty($active_start)) {
    	    return false;
	    }
    	
    	$where = ['store_id', $store_id];
    	$sharp = self::where($where)->all()->toArray();
    	if(count($sharp) <= 0){return true;}
    	
    	foreach ($sharp as $k => $v) {
    		if($v['active_end'] >= $active_start) {
    		    return $v['active_end'];
		    }
	    }
    	
    	return true;
    }
	
	/**
	 * 判断该商品是否参与了秒杀活动
	 * @param int $store_id
	 * @param $goods_id
	 * @return bool
	 */
    static public function checkThisGoodsIsInSharp($store_id = 0, $goods_id)
    {
        if (empty($store_id)) {
            return false;
        }
        $time = Carbon::now();
        $where = [];
        $where[] = ['store_id', $store_id];
        $where[] = ['active_start', '<', $time];
        $where[] = ['active_end', '>', $time];
        //$sharp = self::where($where)->with(['sharpGoods:id,sharp_id'])->first();
        $sharp = SharpToGoods::where('goods_id', $goods_id)->with(['sharp' => function ($q) use ($where){
        	$q->where($where);
        }])->first()->toArray();
        
        if (empty($sharp)) {
            return false;
        }
        
        if (isset($sharp['sharp']) && !empty($sharp['sharp'])) {
            return true;
        } else {
        	return false;
        }
    }
}
